#!/usr/bin/env python3
# encoding: utf-8
# @author : hujincheng
# @time : 2020/4/11 17:33

import pymysql
from DBUtils.PooledDB import PooledDB

"""
连接老库
"""


class MysqlClientOld(object):
    __pool = None

    def __init__(self, mincached=10, maxcached=20, maxshared=10, maxconnections=200, blocking=True, maxusage=100,
                 setsession=None, reset=True, host='rm-bp1g3307unb5t8tk5po.mysql.rds.aliyuncs.com',
                 port=3306, db='quanfan', user='old_db', passwd='old_db123456', charset='utf8'):

        if not self.__pool:
            self.__class__.__pool = PooledDB(pymysql, mincached, maxcached, maxshared, maxconnections, blocking,
                                             maxusage,
                                             setsession, reset, host=host, port=port, db=db, user=user, passwd=passwd,
                                             charset=charset,
                                             cursorclass=pymysql.cursors.DictCursor)
            self._conn = None
            self._cursor = None
            self.__get_conn()

    def __get_conn(self):
        self._conn = self.__pool.connection()
        self._cursor = self._conn.cursor()

    def close(self):
        try:
            self._cursor.close()
            self._conn.close()
        except Exception as e:
            print(e)

    def __execute(self, sql, param=()):
        count = self._cursor.execute(sql, param)
        print(count)

        return count

    def select_one(self):
        result = self._cursor.fetchone()

        return result

    def select_all(self):
        result = self._cursor.fetchall()

        return result

    def select_many(self, num):
        result = self._cursor.fetchmany(num)

        return result

    def execute(self, sql, param=()):
        count = self._cursor.execute(sql, param)
        print(count)

        return count

    def begin(self):
        """
        开启事务
        :return:
        """
        self._conn.autocommit(0)

    def end(self, option="commit"):
        """
        结束事务
        :return:
        """
        if option == "commit":
            self._conn.autocommit()
        else:
            self._conn.rollback()

    def dispose(self, isEnd=1):
        if isEnd == 1:
            self._cursor.end("commit")

        else:
            self._cursor.end("rollback")

        self._cursor.close()
        self._conn.close()

        pass
